import { Tournament } from './entities/tournament.entity';
import { Injectable } from '@nestjs/common';
import { TournamentService } from './tournament.service';
import { RedisService } from '../common/services/redis.service';

@Injectable()
export class TournamentCacheService {
  constructor(
    private readonly redisService: RedisService,
    private readonly tournamentService: TournamentService,
  ) {}

  private findDetailByIdKey = 'tournament:findDetailById';

  async handleTournamentUpdate(payload: any) {
    console.log('handleTournamentUpdate payload', payload.id);
    await this.deleteDetailById(payload.id);
  }

  async findDetailById(tournamentId: number) {
    const res = await this.redisService.get(
      `${this.findDetailByIdKey}:${tournamentId}`,
    );
    if (!res) {
      console.log('findDetailById not cache, id', tournamentId);
      const detail = await this.tournamentService.findDetailById(tournamentId);
      await this.setDetailById(tournamentId, detail);
      return detail;
    }
    return res ? JSON.parse(res) : null;
  }

  async setDetailById(tournamentId: number, detail: Tournament) {
    await this.redisService.set(
      `${this.findDetailByIdKey}:${tournamentId}`,
      JSON.stringify(detail),
    );
  }

  async deleteDetailById(tournamentId: number) {
    await this.redisService.delete(`${this.findDetailByIdKey}:${tournamentId}`);
  }
}
